﻿using System;
using System.IO;
using System.Web;
using Newtonsoft.Json.Linq;

namespace Noria.Web.Utility
{
    public class UploadHandler : IHttpHandler
    {
        // Create a logger for use in this class
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod != "POST")
                throw new MethodNotAllowedException();

            var name = context.Request.QueryString["name"];
            var gen = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss.fff_") + name;
            var path = Path.Combine(context.Server.MapPath("tmp"), gen);

            var length = context.Request.ContentLength;
            var buffer = context.Request.BinaryRead(length);

            System.IO.File.WriteAllBytes(path, buffer);
            log.InfoFormat("Upload file {0} [{1}] to {2}", name, length, path);

            context.Response.ContentType = "application/json";
            context.Response.Write(JObject.FromObject(new { name = gen }).ToString());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}